package gui;

import java.awt.BorderLayout;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;

import javax.swing.JOptionPane;
import javax.swing.JPasswordField;

import utils.JDBCUtil;

public class Register extends javax.swing.JFrame {

	/**
	 * Creates new form Register
	 */
	public Register() {
		initComponents();
	}

	/**
	 * This method is called from within the constructor to initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is always
	 * regenerated by the Form Editor.
	 */
	@SuppressWarnings("unchecked")
	// <editor-fold defaultstate="collapsed" desc="Generated Code">
	private void initComponents() {

		jLabel3 = new javax.swing.JLabel();
		jLabel4 = new javax.swing.JLabel();
		jLabel5 = new javax.swing.JLabel();
		userNameTextField = new javax.swing.JTextField();
		passwordTextField = new javax.swing.JTextField();
		submitButton = new javax.swing.JButton();

		setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
		   
	      //设置背景图片

	        javax.swing.ImageIcon  background = new javax.swing.ImageIcon(getClass().getResource("/image/jmu2.jpg"));  
	        javax.swing.JLabel backImage;  
	        javax.swing.JPanel backPanel;  
	        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
	        setTitle("登录界面");
	        backImage = new javax.swing.JLabel(background);  
	        backImage.setBounds(0, 0, background.getIconWidth(),background.getIconHeight());  
	        backPanel = (javax.swing.JPanel) this.getContentPane();  
	        backPanel.setOpaque(false);  
	       this.getLayeredPane().setLayout(null);  
	       this.getLayeredPane().add(backImage, new Integer(Integer.MIN_VALUE));  
	        backPanel.setLayout(new BorderLayout());  

		setTitle("注册界面");

		jLabel3.setText("注册");

		jLabel4.setText("账号");

		jLabel5.setText("密码");
		submitButton.setText("提交");
		submitButton.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				submitButtonActionPerformed(evt);
			}
		});

		javax.swing.GroupLayout layout = new javax.swing.GroupLayout(
				getContentPane());
		getContentPane().setLayout(layout);
		layout.setHorizontalGroup(layout
				.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(
						layout.createSequentialGroup()
								.addGap(96, 96, 96)
								.addGroup(
										layout.createParallelGroup(
												javax.swing.GroupLayout.Alignment.LEADING)
												.addGroup(
														layout.createSequentialGroup()
																.addGap(50, 50,
																		50)
																.addComponent(
																		jLabel3))
												.addGroup(
														layout.createSequentialGroup()
																.addGroup(
																		layout.createParallelGroup(
																				javax.swing.GroupLayout.Alignment.LEADING)
																				.addComponent(
																						jLabel4,
																						javax.swing.GroupLayout.PREFERRED_SIZE,
																						35,
																						javax.swing.GroupLayout.PREFERRED_SIZE)
																				.addComponent(
																						jLabel5,
																						javax.swing.GroupLayout.PREFERRED_SIZE,
																						47,
																						javax.swing.GroupLayout.PREFERRED_SIZE))
																.addGap(18, 18,
																		18)
																.addGroup(
																		layout.createParallelGroup(
																				javax.swing.GroupLayout.Alignment.LEADING)
																				.addComponent(
																						passwordTextField)
																				.addComponent(
																						userNameTextField,
																						javax.swing.GroupLayout.PREFERRED_SIZE,
																						128,
																						javax.swing.GroupLayout.PREFERRED_SIZE))))
								.addGap(111, 111, 111))
				.addGroup(
						layout.createSequentialGroup()
								.addGap(132, 132, 132)
								.addComponent(submitButton)
								.addContainerGap(
										javax.swing.GroupLayout.DEFAULT_SIZE,
										Short.MAX_VALUE)));
		layout.setVerticalGroup(layout
				.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(
						layout.createSequentialGroup()
								.addGap(73, 73, 73)
								.addComponent(jLabel3)
								.addGap(24, 24, 24)
								.addGroup(
										layout.createParallelGroup(
												javax.swing.GroupLayout.Alignment.LEADING)
												.addComponent(userNameTextField)
												.addComponent(jLabel4))
								.addGap(28, 28, 28)
								.addGroup(
										layout.createParallelGroup(
												javax.swing.GroupLayout.Alignment.LEADING)
												.addComponent(passwordTextField)
												.addComponent(jLabel5))
								.addGap(30, 30, 30).addComponent(submitButton)
								.addGap(65, 65, 65)));

		pack();
	}// </editor-fold>

	private void userNameTextFieldActionPerformed(java.awt.event.ActionEvent evt) {
		// TODO add your handling code here:

	}

	// 判断用户名是否已经被注册
	private boolean checkUserNameExist(String nowName) {
		// TODO add your handling code here:
		Connection conn = null;
		PreparedStatement pstat = null;
		ResultSet rs = null;
		boolean flag = false;
		String sql = "select * from user where userName like ?";
		try {
			conn = JDBCUtil.getConnection();
			pstat = (PreparedStatement) conn.prepareStatement(sql);
			pstat.setString(1, nowName);
			rs = pstat.executeQuery();
			while (rs.next()) {
				String name = rs.getString("userName");
				if (name.equals(nowName)) {
					flag = true;
				}
			}

		} catch (SQLException sqle) {
			sqle.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			JDBCUtil.realeaseAll(rs, pstat, conn);
		}
		return flag;
	}

	private void submitButtonActionPerformed(java.awt.event.ActionEvent evt) {
		String userName = userNameTextField.getText();
		String password = passwordTextField.getText();
		if (userName.equals("") && password.equals("")) {
			JOptionPane.showMessageDialog(null, "用户名密码不能都为空");
		} else if (userName.equals("")) {
			JOptionPane.showMessageDialog(null, "用户名不能为空");
		} else if (password.equals("")) {
			JOptionPane.showMessageDialog(null, "密码不能为空");
		} else if (checkUserNameExist(userName)) {
			JOptionPane.showMessageDialog(null, "对不起!用户名已被注册，请更换。");
		} else {
			User user = new User(userName, password);
			if (isWriteUser(user)) {
				JOptionPane.showMessageDialog(null, "注册成功！");

			}
		}

	}

	/**
	 * @param args
	 *            the command line arguments
	 */
	public static void main() {
		/* Set the Nimbus look and feel */
		// <editor-fold defaultstate="collapsed"
		// desc=" Look and feel setting code (optional) ">
		/*
		 * If Nimbus (introduced in Java SE 6) is not available, stay with the
		 * default look and feel. For details see
		 * http://download.oracle.com/javase
		 * /tutorial/uiswing/lookandfeel/plaf.html
		 */
		try {
			for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager
					.getInstalledLookAndFeels()) {
				if ("Nimbus".equals(info.getName())) {
					javax.swing.UIManager.setLookAndFeel(info.getClassName());
					break;
				}
			}
		} catch (ClassNotFoundException ex) {
			java.util.logging.Logger.getLogger(Register.class.getName()).log(
					java.util.logging.Level.SEVERE, null, ex);
		} catch (InstantiationException ex) {
			java.util.logging.Logger.getLogger(Register.class.getName()).log(
					java.util.logging.Level.SEVERE, null, ex);
		} catch (IllegalAccessException ex) {
			java.util.logging.Logger.getLogger(Register.class.getName()).log(
					java.util.logging.Level.SEVERE, null, ex);
		} catch (javax.swing.UnsupportedLookAndFeelException ex) {
			java.util.logging.Logger.getLogger(Register.class.getName()).log(
					java.util.logging.Level.SEVERE, null, ex);
		}
		// </editor-fold>

		/* Create and display the form */
		java.awt.EventQueue.invokeLater(new Runnable() {
			public void run() {
				javax.swing.JFrame registerJFrame = new Register();
				registerJFrame.setVisible(true);
				registerJFrame.setSize(350, 350);
				registerJFrame.setResizable(false);
			}
		});
	}

	public boolean isWriteUser(User user) {
		Connection conn = null;
		PreparedStatement pstat = null;
		String sql = "insert into user(userName,password)values(?,?) ";
		int result = -1;

		try {
			conn = JDBCUtil.getConnection();
			pstat = (PreparedStatement) conn.prepareStatement(sql);
			pstat.setString(1, user.getUserName());
			pstat.setString(2, user.getPassword());
			result = pstat.executeUpdate();

		} catch (SQLException sqle) {
			sqle.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			JDBCUtil.realeaseAll(null, pstat, conn);
		}
		return result > 0 ? true : false;
	}

	private javax.swing.JButton submitButton;
	private javax.swing.JLabel jLabel3;
	private javax.swing.JLabel jLabel4;
	private javax.swing.JLabel jLabel5;
	private javax.swing.JTextField passwordTextField;
	private javax.swing.JTextField userNameTextField;
	// End of variables declaration
}
